package com.cqeec.myblog.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.cqeec.myblog.model.Blogger;
import com.cqeec.myblog.util.DbUtil;

public class BloggerDaoImpl implements BloggerDao {

	/**
	 * 获取数据库中用户总数
	 */
	@Override
	public int count() throws ClassNotFoundException, SQLException {
		// 获取数据库连接对象
		Connection conn = DbUtil.getDbConnection();
		// 创建语句对象
		Statement state = conn.createStatement();
		// 执行SQL语句，获取结果
		ResultSet rs = state.executeQuery("SELECT COUNT(*) FROM Blogger");
		rs.next();
		return rs.getInt(1);
	}

	/**
	 * 根据用户id查找用户
	 */
	@Override
	public Blogger selectById(String id) throws ClassNotFoundException, SQLException {
		Connection conn = DbUtil.getDbConnection();
		// Statement state = conn.createStatement();
		// ResultSet rs = state.executeQuery("SELECT * FROM Blogger WHERE id='" + id +
		// "'");

		PreparedStatement ps = conn.prepareStatement("SELECT * FROM Blogger WHERE id=?");
		ps.setString(1, id);
		ResultSet rs = ps.executeQuery();

		Blogger blogger = null;
		if (rs.next()) {
			blogger = new Blogger();
			blogger.setId(id);
			blogger.setName(rs.getString("name"));
			blogger.setGender(rs.getString("gender"));
			blogger.setPassword(rs.getString("password"));
			blogger.setNickname(rs.getString("nickname"));
			blogger.setIntroduction(rs.getString("introduction"));
			blogger.setQq(rs.getString("QQ"));
			blogger.setEmail(rs.getString("email"));
		}
		return blogger;
	}

	/**
	 * 根据用户名和密码查找用户
	 */
	@Override
	public Blogger findByNameAndPassword(String name, String password) throws ClassNotFoundException, SQLException {
		Connection conn = DbUtil.getDbConnection();
		PreparedStatement ps = conn
				.prepareStatement("SELECT * FROM Blogger WHERE (name=? OR nickname=?) AND password=?");
		ps.setString(1, name);
		ps.setString(2, name);
		ps.setString(3, password);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			Blogger blogger = new Blogger();
			blogger.setId(rs.getString("id"));
			blogger.setName(rs.getString("name"));
			blogger.setNickname(rs.getString("nickname"));
			return blogger;
		} else {
			return null;
		}
	}

}
